package com.intretech.tj.light.service;


import com.intretech.tj.light.Light;
import jakarta.enterprise.context.ApplicationScoped;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;

import org.yaml.snakeyaml.representer.Representer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Paths;

@Slf4j
@ApplicationScoped
public class YamlService {

    public YamlService() {
//        loadFromYaml("light.yaml", Light[].class);
    }

    /**
     * 将给定的对象实例序列化为YAML字符串并保存到与JAR包同级的指定文件中。
     *
     * @param instance 要保存的对象实例
     * @param fileName 保存的文件名（不包含路径）
     */
    public void saveAsYaml(Object instance, String fileName) {
        // 设置YAML的序列化配置
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); // 设置块状风格
        // 配置 Representer 禁用全局标签
        Representer representer = new Representer(new DumperOptions());
        representer.getPropertyUtils().setSkipMissingProperties(true);

        Yaml yaml = new Yaml(representer, options);


        // 序列化对象为YAML字符串
        String yamlString = yaml.dump(instance);

        try {
            // 获取当前JAR包所在的目录
            String jarDir = Paths.get(YamlService.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toString();

            // 指定保存的文件路径（假设与JAR包同级）
//            jarDir.split("/").length
            String filePath = "./" + fileName;

            // 写入文件
            File file = new File(filePath);
            try (FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(yamlString.getBytes());
            }
            log.info("YAML saved to: {}", filePath);
        } catch (Exception e) {
            log.error("Error saving YAML: {}", e.getMessage());
        }
    }

    /**
     * 如果YAML文件不存在，则根据指定的类生成一个包含默认值的YAML文件。
     *
     * @param fileName YAML文件名
     */
    public boolean saveIfNotExists(String fileName) {

        try {
            String jarDir = Paths.get(YamlService.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toString();
            // 指定保存的文件路径（假设与JAR包同级）
            String filePath = "." + "/" + fileName;
            File file = new File(filePath);
            return file.exists();
        } catch (Exception e) {
            log.error("Error saveIfNotExists YAML: {}", e.getMessage());
            return false;
        }
        // 获取当前JAR包所在的目录

        //            DumperOptions options = new DumperOptions();
        //            options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        //            Yaml yaml = new Yaml(options);
        //
        //            StringBuilder yamlContent = new StringBuilder();
        //            for (Map.Entry<String, Object> entry : defaults.entrySet()) {
        //                yamlContent.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
        //            }
        //
        //            try {
        //
        //                try (FileOutputStream fos = new FileOutputStream(file)) {
        //                    fos.write(yamlContent.toString().getBytes());
        //                }
        //
        //            } catch (Exception e) {
        //                log.error("Error saveIfNotExists YAML: {}", e.getMessage());
        //            }

    }


    /**
     * 从YAML文件中加载数据并实例化为指定的类型。
     *
     * @param fileName YAML文件的路径
     * @param clazz     需要反序列化的类
     * @param <T>       类型参数
     * @return 实例化后的对象
     */
    public <T> T loadFromYaml(String fileName, Class<T> clazz) {
        LoaderOptions loaderOptions = new LoaderOptions();
        loaderOptions.setTagInspector(tag -> true);
        Yaml yaml = new Yaml(loaderOptions);
        try {
            // 获取当前JAR包所在的目录
            String jarDir = Paths.get(YamlService.class.getProtectionDomain().getCodeSource().getLocation().toURI()).toString();
            // 指定保存的文件路径（假设与JAR包同级）
            String filePath = "." + "/" + fileName;

//            saveIfNotExists(clazz, filePath, Map.of("key", "value"));

            try (InputStream inputStream = new FileInputStream(new File(filePath))) {
                T data = yaml.loadAs(inputStream, clazz);

                if (clazz == Light[].class) {
                    return data;
                } else {
                    throw new IllegalArgumentException("Unsupported type for deserialization: " + clazz);
                }
            }
        } catch (Exception e) {
            log.error("Error Read YAML: {}", e.getMessage());
            return null;
        }
    }
}
